﻿#include <QApplication>
#include "cruntimesetting.h"
#include <QDir>
#include <QCoreApplication>
#include <QJsonParseError>
#include <QJsonObject>
#include <QFile>
#include <QDebug>
#include <QJsonArray>
#include <QSettings>
#include "common.h"

#define AUTO_RUN     "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run"
#define AUTO_RUN_KEY "SsScreenSaver"
namespace ss {

RunConfig CRuntimeSetting::s_config;
RunConfig CRuntimeSetting::s_previewConfig;

CRuntimeSetting::CRuntimeSetting()
{
}

void CRuntimeSetting::Update2File()
{
    QFile file;
    do
    {
        QString strConfigPath = QDir(QCoreApplication::applicationDirPath()).absoluteFilePath("run.json");
        qDebug() << strConfigPath;

        file.setFileName(strConfigPath);
        if (!file.open(QIODevice::Truncate | QIODevice::WriteOnly))
        {
            qWarning() << __FUNCTION__ << ": open file[ " << strConfigPath << " ] failed!";
            break;
        }
        QJsonDocument doc;
        QJsonObject obj;
        obj["lockspan"] = s_config.nLockSpan;
        obj["showsecond"] = s_config.bShowSecond;
        obj["showdate"] = s_config.bShowDate;
        obj["runonstartup"] = s_config.bRunOnStartup;
        obj["fontsizefortime"] = s_config.nFontSizeForTime;
        obj["fontsizefordate"] = s_config.nFontSizeForDate;
        obj["font"] = s_config.font;
        obj["sentence"] = s_config.sentence;
        QJsonArray arr;
        for (int i = 0; i < s_config.vecComments.size(); ++i) {
            arr.append(s_config.vecComments[i]);
        }
        obj["comments"] = arr;

        doc.setObject(obj);
        file.write(doc.toJson(QJsonDocument::Indented));

    } while(0);

    if (file.isOpen())
    {
        file.close();
    }
}

bool CRuntimeSetting::Initialize()
{
    QFile file;
    QString strConfigPath = QDir(QCoreApplication::applicationDirPath()).absoluteFilePath("run.json");
    qDebug() << strConfigPath;
    file.setFileName(strConfigPath);
    if (!file.open(QIODevice::ReadOnly))
    {
        qWarning() << __FUNCTION__ << ": open file[ " << strConfigPath << " ] failed!";
        return false;
    }

    QJsonParseError error;
    QJsonDocument doc = QJsonDocument::fromJson(file.readAll(), &error);
    if (error.error != QJsonParseError::NoError)
    {
        qWarning() << __FUNCTION__ << ": fromJson(file.readAll) [ " << strConfigPath << " ] failed!";
        return false;
    }

    file.close();

    QJsonObject obj = doc.object();
    QStringList keys = obj.keys();
    for (auto const& key : keys)
    {
        qDebug() << "Json key[" << key << "]=" << (obj[key].isString()? obj[key].toString() : (obj[key].isArray()? "array" : QString::number(obj[key].toInt())));
    }
    s_config.nLockSpan = max(MIN_LOCK_SPAN, min(MAX_LOCK_SPAN, obj["lockspan"].toInt()));
    s_config.bShowSecond = obj["showsecond"].toBool();
    s_config.bShowDate = obj["showdate"].toBool();
    s_config.bRunOnStartup = obj["runonstartup"].toBool();
    s_config.nFontSizeForTime = max(MAX_TIME_FONT_POINTSIZE, min(MIN_TIME_FONT_POINTSIZE, obj["fontsizefortime"].toInt()));
    s_config.nFontSizeForDate = max(MAX_DATE_FONT_POINTSIZE, min(MIN_DATE_FONT_POINTSIZE, obj["fontsizefordate"].toInt()));
    s_config.nFontSizeForSentence = max(MAX_SENTENCE_FONT_POINTSIZE, min(MIN_SENTENCE_FONT_POINTSIZE, obj["fontsizeforsentence"].toInt()));
    s_config.font = obj["font"].toString();
    s_config.sentence = obj["sentence"].toString();
    s_config.vecComments.clear();
    if (obj["comments"].isArray())
    {
        QJsonArray arr = obj["comments"].toArray();
        for (auto i = 0; i < arr.size(); ++i)
        {
            s_config.vecComments.push_back(arr.at(i).toString());
        }
    }
    else if (obj["comments"].isString())
    {
        s_config.vecComments.push_back(obj["comments"].toString());
    }
    s_previewConfig = s_config;
    return true;
}

const RunConfig &CRuntimeSetting::GetConfig()
{
    return s_config;
}

const RunConfig &CRuntimeSetting::GetPreviewConfig()
{
    return s_previewConfig;
}

int CRuntimeSetting::GetLockSpan()
{
    return s_config.nLockSpan;
}

bool CRuntimeSetting::IsShowSecond()
{
    return s_config.bShowSecond;
}

bool CRuntimeSetting::IsShowDate()
{
    return s_config.bShowDate;
}

bool CRuntimeSetting::IsRunOnStartup()
{
    return s_config.bRunOnStartup;
}

void CRuntimeSetting::SetPreviewConfig(bool bShowSecond, bool bShowDate, const QString &sentence)
{
    s_previewConfig.bShowDate = bShowDate;
    s_previewConfig.bShowSecond = bShowSecond;
    s_previewConfig.sentence = sentence;
}



void CRuntimeSetting::SetConfig(bool bShowSecond, bool bShowDate, unsigned int nLockSpan, bool bRunOnStartup, const QString& sentence)
{
    s_config.bShowDate = bShowDate;
    s_config.bShowSecond = bShowSecond;
    nLockSpan = max(MIN_LOCK_SPAN, min(MAX_LOCK_SPAN, nLockSpan));
    s_config.nLockSpan = nLockSpan * 1000;
    s_config.bRunOnStartup = bRunOnStartup;
    s_config.sentence = sentence;
    s_previewConfig = s_config;
    // 更新到文件
    Update2File();
    // 写注册表
    SetRunOnStartupState(bRunOnStartup);
}

void CRuntimeSetting::SetRunOnStartupState(bool bRunOnStartup)
{
    QSettings settings(AUTO_RUN, QSettings::NativeFormat);
    if (bRunOnStartup)
    {
        settings.setValue(AUTO_RUN_KEY, QDir::toNativeSeparators(QApplication::applicationFilePath()));
    }
    else
    {
        settings.remove(AUTO_RUN_KEY);//移除注册表
    }
}



}
